package com.yswy.common.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description java执行linux命令工具类
 * @Version 1.0
 **/
@Slf4j
public class CommandUtil {


    public static void main(String[] args) {
//        String s = execCMD("C:\\Users\\mxy\\Desktop\\packagesh.sh", new String[]{"11" , "22.apk"}, 10);
//        System.out.println(s);
        String path = "C:\\Users\\mxy\\Desktop\\";
        String packageId = "123456";
        long start = System.currentTimeMillis() ;
        String cmd = "java -jar "+path+"walle-cli-all.jar " +
                "put -c meituan " +
                "-e packageId="+packageId +" " +
                path + "goface_jlyq001_2.2.2_22_release.apk " +
                path + "22.apk";

        System.out.println(cmd);
        String s = execCMD(cmd, null, 10);
        System.out.println(s);
        long stop = System.currentTimeMillis() ;
        System.out.println(stop-start);
    }



    /**
     * 命令执行,超时退出
     * @param cmd
     * @param envs
     * @param timeout 秒
     * @return
     */
    public static String execCMD(String cmd, String[] envs, int timeout) {
        Process process = null;
        StringBuilder sbStd = new StringBuilder();
        StringBuilder sbErr = new StringBuilder();

        boolean isTimeOut = false;//是否超时的标识, 默认false
        long start = System.currentTimeMillis() / 1000;
        try {
            if (envs == null) {
                process = Runtime.getRuntime().exec(cmd);
            } else {
//                process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd }, envs);
                process = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", cmd }, envs);

            }

            BufferedReader brStd = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader brErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = null;

            while (true) {
                if (brStd.ready()) {
                    line = brStd.readLine();
                    sbStd.append(line + "\n");
                    continue;
                }
                if (brErr.ready()) {
                    line = brErr.readLine();
                    sbErr.append(line + "\n");
                    continue;
                }

                if (process != null) {
                    try {
                        process.exitValue();
                        break;
                    } catch (IllegalThreadStateException e) {
                    }
                }

                if (System.currentTimeMillis() / 1000 - start > timeout) {
                    isTimeOut = true;
                    sbErr.append("\n命令执行超时退出.");
                    break;
                }

                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }

        if (isTimeOut) {
            //如果超时,就抛出异常
            throw new IllegalArgumentException("上传超时");
        }

        if (sbErr.length()>0) {
            return sbErr.toString();
        } else {
            return sbStd.toString();
        }
    }


    //直接执行,没有超时关闭
    public static String executeLinuxCmd(String cmd) {
        System.out.println("got cmd job : " + cmd);
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(cmd);

            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            // System.out.println("[check] now size \n"+bs.readLine());
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[8192];
            for (int n; (n = in.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
            }
            System.out.println("job result [" + out.toString() + "]");
            in.close();
            // process.waitFor();
            process.destroy();
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




    /**
     * 通过obsutil内网上传文件,返回一个下载地址
     * targetFilePath 目标文件所在服务器地址; userId 用户id; fileName文件全名称,如XXX.ZIP
     * @Date 16:53 2020/11/4
     * @Param [targetFilePath, userId, fileName]
     * @return java.lang.String
     **/
    public static String inUploadFileByObsUtil(String targetFilePath,Integer userId,String fileName) {
        String objectUrl = null;
        try {
            long startOBS = System.currentTimeMillis();
            log.info("====>inUploadFileByObsUtil:开始上传压缩文件到华为云obs...");
            //这里改为运行linux服务器的命令,通过obsUtil 内网上传,等上传成功后,拼接下载地址存入数据库
            String cmd = "/usr/local/obsutil/startObsutilUpload.sh " + targetFilePath + " " + userId;
            //上传文件,最多执行2分钟
            String result = CommandUtil.execCMD(cmd, null, 120);
            log.info("====>inUploadFileByObsUtil:result:" + result);
//        String objectUrl = huaWeiYunOBSUtil.largeUpload(fileName, "systemFiles", newZipFile);
            objectUrl = Const.OBS_URL + "weigou-files/systemPackage/" + userId + File.separator + fileName;
            log.info("====>inUploadFileByObsUtil:下载地址:" + objectUrl);
            log.info("====>inUploadFileByObsUtil:上传压缩文件到华为云obs完成...");
            long endOBS = System.currentTimeMillis();
            log.info("====>inUploadFileByObsUtil:上传文件到华为云obs结束时间()秒:" + ((endOBS - startOBS) / 1000));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return objectUrl;
    }


}
